<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import SceneOverview from './components/SceneOverview.vue'
import StageTitle from './components/StageTitle.vue'
import StageContentCard from './StageContentCard/index.vue'
import TimeLine from './components/TimeLine.vue'
import { message } from 'ant-design-vue'
import type { PhaseType } from '@/types/micro-scene'
import { useUserStore } from '@/stores/useUserStore';
import { EditOutlined } from '@ant-design/icons-vue'
import TimeLineEditor from './components/TimeLineEditor.vue'
import { useRoute, useRouter } from 'vue-router'
import { getMicroSceneBeginEndIdApi, getScenePhaseList } from '@/api/MicroScene/MicroSceneDetailApi'
const props = defineProps<{
  microSceneId: string
}>()
const userStore = useUserStore();
const route = useRoute();
const router = useRouter();
// 选中阶段
const currentPhaseId = ref('')
// 最后活跃阶段
const lastActivePhaseId = ref('')

const showEdit = computed(() => {
  // 是否具有该微场景的编辑权限，而不简单判断是否为教师
  return userStore.isEditMicroScene
})

// 初始化值必须要有，不然TimeLine组件渲染错误
const phaseList = ref<PhaseType[]>([
  {
    phaseId: '1',
    phaseTitle: '阶段1',
    sortOrder: 1,
  },
])

// 开课记录ID
const beginEndId = ref('540881188246528');

// 获取最新开课记录
const getLatestBeginEndId = async () => {
  try {
    const response = await getMicroSceneBeginEndIdApi(props.microSceneId)
    if (response.length > 0)
      beginEndId.value = response[0].beginEndId
  }
  catch (error) {
    message.error('获取开课记录失败')
    console.error('Error fetching begin end id:', error);
  }
}

const findPhase = (phaseId: string) => {
  return phaseList.value.find(phase => phase.phaseId === phaseId)
}

const handlePhaseClick = (phaseId: string) => {
  // 选中的阶段sortOrder如果大于最后活跃阶段 sortOrder，则无法选中
  const selectPhaseIndex = phaseList.value.findIndex(phase => phase.phaseId === phaseId)
  let lastActivePhaseIndex = phaseList.value.findIndex(phase => phase.phaseId === lastActivePhaseId.value)
  if (selectPhaseIndex === -1) {
    message.error('阶段不存在')
    return
  }
  // 如果活跃阶段不存在那么默认选中第一个阶段
  if (lastActivePhaseIndex === -1) {
    lastActivePhaseId.value = phaseList.value[0].phaseId
    lastActivePhaseIndex = 0
  }
  // note: 如果是具有编辑权限的人，直接直接切换
  if (selectPhaseIndex > lastActivePhaseIndex && !showEdit.value) {
    message.error('请先完成最新阶段后切换')
    return
  }
  currentPhaseId.value = phaseId
}

const visible = ref(false)

const handleEditTimeLine = (show: boolean) => {
  visible.value = show
}

// 获取阶段列表
const getPhaseList = async () => {
  try {
    const response = await getScenePhaseList(props.microSceneId)
    phaseList.value = response.map((item: PhaseType) => ({
      phaseId: item.phaseId,
      phaseTitle: item.phaseTitle,
      sortOrder: item.sortOrder,
    }))
    // 默认选中第一个阶段
    if (currentPhaseId.value === '' && phaseList.value.length > 0)
      currentPhaseId.value = phaseList.value[0].phaseId

    // TODO: 设置最后活跃阶段为最后一个元素，等后端处理过后直接删除
    if (phaseList.value.length > 0)
      lastActivePhaseId.value = phaseList.value[phaseList.value.length - 1].phaseId
  }
  catch (error) {
    message.error('获取阶段列表失败')
    console.error('Error fetching phase list:', error);
  }
}

// 在组件挂载时获取用户关于这个微场景的权限
onMounted(async () => {
  await userStore.setIsMicroScenePermission(props.microSceneId);
  if (!userStore.isViewMicroScene) {
    message.error('您没有权限查看该微场景');
    // 跳转到首页广场
    router.push('/user/homepagesquare');
  }
  getPhaseList()
  getLatestBeginEndId()
});
</script>

<template>
  <div class="w-full h-full overflow-y-auto">
    <!-- 场景介绍区域 -->
    <section class="w-full">
      <div class="container mx-auto px-4">
        <!-- 这里将放置场景介绍内容 -->
        <SceneOverview />
      </div>
    </section>

    <!-- 时间线编辑按钮 -->
    <div v-if="showEdit" class="w-full flex justify-end pr-20 mt-2">
      <a-button type="primary" @click="handleEditTimeLine(true)">
        编辑阶段
        <template #icon>
          <EditOutlined />
        </template>
      </a-button>
    </div>
    <TimeLineEditor :visible="visible" :current-phase-id="currentPhaseId" :phase-list="phaseList" @update:visible="handleEditTimeLine" @update:current-phase-id="handlePhaseClick" @update:phase-list="getPhaseList" />
    <!-- 时间线区域 -->
    <section class="w-full">
      <div class="container mx-auto px-4">
        <!-- 这里将放置时间线组件 -->
        <TimeLine :selected-phase-id="currentPhaseId" :phases="phaseList" :last-active-phase-id="lastActivePhaseId" @update:selected-phase="handlePhaseClick" />
      </div>
    </section>

    <!-- 阶段名称区域 -->
    <section class="w-full mt-2">
      <div class="container mx-auto px-4">
        <!-- 这里将放置阶段名称内容 -->
        <StageTitle :index="phaseList.findIndex(phase => phase.phaseId === currentPhaseId) + 1" :phase="findPhase(currentPhaseId)" />
      </div>
    </section>

    <!-- 具体阶段内容卡片区域 -->
    <section class="w-full mt-4">
      <div class="container mx-auto px-4">
        <!-- 只有当currentPhaseId存在时才加载组件 -->
        <StageContentCard
          v-if="currentPhaseId"
          :phase-id="currentPhaseId"
          :begin-end-id="beginEndId"
        />
        <div v-else class="text-center text-gray-500">
          加载中...
        </div>
      </div>
    </section>

    <!-- 空白 -->
    <div class="h-[5rem]" />
  </div>
</template>
